<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/8
 * Time: 9:33
 */

namespace plugin\admin\app\logic\admin;


use plugin\admin\app\common\Auth;
use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\admin\Admin;
use plugin\admin\app\model\admin\AdminRole;
use support\Request;
use support\Response;

class ManageLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new Admin();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['isdel'] = 0;
        $query = $this->doSelect($where, $field, $order);
        if ($format === 'select') {
            return $this->formatSelect($query->get());
        }
        $paginator = $query->paginate($limit);
        $items = $paginator->items();
        $admin_ids = array_column($items, 'id');
        $roles = AdminRole::whereIn('admin_id', $admin_ids)->get();
        $roles_map = [];
        foreach ($roles as $role) {
            $roles_map[$role['admin_id']][] = $role['role_id'];
        }
        $login_admin_id = \request()->curAdminId;
        foreach ($items as $index => $item) {
            $admin_id = $item['id'];
            $items[$index]['roles'] = isset($roles_map[$admin_id]) ? implode(',', $roles_map[$admin_id]) : '';
            $items[$index]['show_toolbar'] = $admin_id != $login_admin_id;
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $paginator->total(), 'data' => $items]);
    }

    public function insert(Request $request): Response
    {
        $data = $this->insertInput($request);
        $count = $this->model->getWhere(['username'=>$data['username'],'isdel'=>0])->count();
        if($count){
            throw new AdminException(4020,'用户名已存在');
        }
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');
        $admin_id = $this->doInsert($data);
        $role_ids = $request->post('roles');
        $role_ids = $role_ids ? explode(',', $role_ids) : [];
        if (!$role_ids) {
            throw new AdminException(4020,'至少选择一个角色组');
        }
        if (!Auth::isSupperAdmin() && array_diff($role_ids, Auth::getScopeRoleIds())) {
            throw new AdminException(4020,'角色超出权限范围');
        }
        AdminRole::where('admin_id', $admin_id)->delete();
        foreach ($role_ids as $id) {
            $admin_role = new AdminRole;
            $admin_role->admin_id = $admin_id;
            $admin_role->role_id = $id;
            $admin_role->save();
        }
        return $this->json(0, 'ok', ['id' => $admin_id]);
    }

    public function update(Request $request): Response
    {
        [$id, $data] = $this->updateInput($request);
        $primary_key = $this->model->getKeyName();
        $admin_id = $request->post($primary_key);
        if (!$admin_id) {
            throw new AdminException(4020,'缺少参数');
        }

        // 不能禁用自己
        if (isset($data['status']) && $data['status'] == 0 && $id == \request()->curAdminId) {
            throw new AdminException(4020,'不能禁用自己');
        }

        // 需要更新角色
        $role_ids = $request->post('roles');
        if ($role_ids !== null) {
            if (!$role_ids) {
                throw new AdminException(4020,'至少选择一个角色组');
            }
            $role_ids = explode(',', $role_ids);

            $is_supper_admin = Auth::isSupperAdmin();
            $exist_role_ids = AdminRole::where('admin_id', $admin_id)->pluck('role_id')->toArray();
            $scope_role_ids = Auth::getScopeRoleIds();
            if (!$is_supper_admin && !array_intersect($exist_role_ids, $scope_role_ids)) {
                throw new AdminException(4020,'无权限更改该记录');
            }
            if (!$is_supper_admin && array_diff($role_ids, $scope_role_ids)) {
                throw new AdminException(4020,'角色超出权限范围');
            }

            // 删除账户角色
            $delete_ids = array_diff($exist_role_ids, $role_ids);
            AdminRole::whereIn('role_id', $delete_ids)->where('admin_id', $admin_id)->delete();
            // 添加账户角色
            $add_ids = array_diff($role_ids, $exist_role_ids);
            foreach ($add_ids as $role_id) {
                $admin_role = new AdminRole;
                $admin_role->admin_id = $admin_id;
                $admin_role->role_id = $role_id;
                $admin_role->save();
            }
        }

        $this->doUpdate($id, $data);
        return $this->json(0);
    }

    public function delete(Request $request): Response
    {
        $primary_key = $this->model->getKeyName();
        $ids = $request->post($primary_key);
        if (!$ids) {
            return $this->json(0);
        }
        $ids = (array)$ids;
        if (in_array(request()->curAdminId, $ids)) {
            throw new AdminException(4020,'不能删除自己');
        }
        if (!Auth::isSupperAdmin() && array_diff($ids, Auth::getScopeAdminIds())) {
            throw new AdminException(4020,'无数据权限');
        }
        $this->model->whereIn($primary_key, $ids)->update(['isdel'=>time(),'updated_at'=>date('Y-m-d H:i:s')]);
        AdminRole::whereIn('admin_id', $ids)->delete();
        return $this->json(0);
    }
}